import cv2


img1= cv2.imread('code_of_teacher/book_cover.jpg',cv2.IMREAD_COLOR)
img2= cv2.imread('code_of_teacher/book_cover.jpg',cv2.IMREAD_COLOR)
gray1= cv2.cvtColor(img1,cv2.COLOR_BGR2GRAY)
gray2= cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)

detector = cv2.xfeatures2d.SIFT_create()
# detector = cv2.ORB_create()
kp1,des1=detector.detectAndCompute(gray1,None)
kp2,des2=detector.detectAndCompute(gray2,None)
# matcher = cv2.FlannBasedMatcher()
# 暴力匹配器
matcher = cv2.BFMatcher()
# 匹配特征描述子
# 我们要找最近和次近的所以k=2
matches = matcher.knnMatch(des1,des2,k=2)
# 计算最近与次近距离的比值，挑选小于阈值的匹配对
good_matches= []
# 进一步挑选这些匹配
for m1,m2 in matches:
    # 使用最近的除以次近的看比值的与阈值的大小
    ratio = m1.distance / m2.distance
    # 满足这个条件表示是一个比较好的匹配，然后存储起来
    if ratio < 0.7:
        good_matches.append(m1)
#使用OpenCV中的方法绘制匹配
dst = cv2.drawMatches(img1,kp1,img2,kp2,good_matches,None)
cv2.imshow('Feature match',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
